<?php

class User {

	public $id;
	public $nome;
	public $cognome;
	public $email;
	public $password;
	public $ruolo;
	
	protected $_ruoli = array ('utente', 'admin');

	//Constructor is called whenever a new object is created.
	//Takes an associative array with the DB row as an argument.
	function __construct($data) {
		
		$this->id = (isset($data['id'])) ? $data['id'] : "";
		$this->nome = (isset($data['nome'])) ? $data['nome'] : "";
		$this->cognome = (isset($data['cognome'])) ? $data['cognome'] : "";
		$this->email = (isset($data['email'])) ? $data['email'] : "";
		$this->password = !empty($data['password']) ? UserTools::cryptPassword($this->email, $data['password']) : ''; 
		$this->ruolo = (isset($data['ruolo'])) ? $data['ruolo'] : "";
	}

	public function save($isNewUser = false) {
		//create a new database object.
		$db = DB::getDB();

		//if the user is already registered and we're
		//just updating their info.
		if(!$isNewUser) {
			//set the data array
			$data = array(
					"nome" => "'$this->nome'",
					"cognome" => "'$this->cognome'",					
					"email" => "'$this->email'",
					"password" => "'$this->password'"
			);

			//update the row in the database
			$db->update($data, 'utente', 'id = '.$this->id);
			
		} else {
		//if the user is being registered for the first time.
			$data = array(
				"nome" => "'$this->nome'",
				"cognome" => "'$this->cognome'",					
				"email" => "'$this->email'",
				"password" => "'$this->password'",
				"ruolo" => "'utente'"
				);

				$this->id = $db->insert($data, 'utente');
		}
		return true;
	}
}
?>